﻿using System;
using wcsServo.cache;
using wcsServo.dao;
using wcsServo.domain;
using wcsServo.entity;

namespace wcsServo.service
{
    public class FuncService
    {
        private TaskService _taskService = new TaskService();
        private StnMappingService _stnMapService = new StnMappingService();
        public ResultData_FUNC ExecFunction(string funcName, string param)
        {
            //初始化过程相关的参数
            ResultData_FUNC result = new ResultData_FUNC
            {
                Code = "0",
                Msg = "success"
            };

            LogEntity logEntity = new LogEntity
            {
                WORK_NAME = "[流程-事件触发]-PLC",
                WORK_PROC = "FuncService.ExecFunction",
                WORK_CODE = "0",
                WORK_MSG = "success",
                CONT_NO = "",
                WORK_SEC = 1,
                CREATOR = 1001,
                CREATOR_NAME = "WCS",
                CREATE_DATE = DateTime.Now
            };

            if (!GlobalCachePool.single_plcItem_dict.TryGetValue(param, out PlcItemEntity item))
            {
                result.Code = "500";
                result.Msg = $"信号点[{param}]未在[PLC_ITEM]表中配置!]";
                return result;
            }

            if ("CREATE_TASK_KX".Equals(funcName))
            {
                //收到信息解析后创建任务
                result = _taskService.CreateTaskByKx(item.STN_NO);
                if (result.Code == "0")
                {
                    result.Writes = "MEM." + param + "=1";
                }
            }
            else if ("CREATE_TASK_XW".Equals(funcName))
            {
                result = _taskService.CreateTaskByXW(item.STN_NO, item.ITEM_VALUE);
                if (result.Code == "0")
                {
                    result.Writes = "MEM." + param + "=1";
                }
            }
            else if ("UPDATE_STN_KX".Equals(funcName))
            {
                result = _stnMapService.UpdateStation(item.STN_NO, item.ITEM_VALUE);
                string itemPc = item.ITEM_NO.Replace("PLC_TO_AGV", "AGV_TO_PLC");
                result.Writes = itemPc + "=1";
            }
            else if ("UPDATE_STN_CP".Equals(funcName))
            {
                result = _stnMapService.UpdateStation(item.STN_NO, item.ITEM_VALUE);
                string itemPc = item.ITEM_NO.Replace("PLC_TO_AGV", "AGV_TO_PLC");
                result.Writes = itemPc + "=0";
            }
            else
            {
                result.Code = "500";
                result.Msg = $"未匹配到相关方法{funcName}";
            }
            //记录日志
            logEntity.CONT_NO = param;
            logEntity.WORK_CODE = result.Code;
            logEntity.WORK_MSG = result.Msg;
            if (!"404".Equals(result.Code))
            {
                DBFactory.Insert2WorkLog(logEntity);
            }

            //根据传入的参数获取对应的站台编号
            return result;
        }
    }
}
